package system;

import java.io.IOException;

import javax.faces.context.FacesContext;

import javax.faces.event.ActionEvent;

import javax.servlet.http.HttpServletRequest;

import javax.faces.application.FacesMessage;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;

import javax.servlet.http.HttpServletResponse;

import weblogic.security.SimpleCallbackHandler;
import weblogic.security.services.Authentication;

import weblogic.servlet.security.ServletAuthentication;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import java.io.IOException;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;

import org.apache.myfaces.trinidad.util.Service;

import view.common.Utils;

public class Login {

    private String _username;
    private String _password;
    private String checklogin;

    public void setUsername(String _username) {
        this._username = _username;
    }

    public String getUsername() {
        return _username;
    }

    public void setPassword(String _password) {
        this._password = _password;
    }

    public String getPassword() {
        return _password;
    }

    public String doLogin() {
        SystemSecurity sercu = new SystemSecurity();
        if (!sercu.isAuthenticated()) {
            String un = _username;
            byte[] pw = _password.getBytes();
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpServletRequest request =
                (HttpServletRequest)ctx.getExternalContext().getRequest();
            CallbackHandler handler =
                new SimpleCallbackHandler(un, pw, "utf-8");
            try {
                Subject mySubject = Authentication.login(handler);
                ServletAuthentication.runAs(mySubject, request);
                ServletAuthentication.generateNewSessionID(request);

                String loginUrl =
                    "/adfAuthentication?success_url=/faces/welcome";
                HttpServletResponse response =
                    (HttpServletResponse)ctx.getExternalContext().getResponse();
                sendForward(request, response, loginUrl);
            } catch (FailedLoginException fle) {
                FacesMessage msg =
                    new FacesMessage(FacesMessage.SEVERITY_ERROR,
                                     "Lỗi đăng nhập",
                                     "Sai tên đăng nhập hoặc mật khẩu!");
                ctx.addMessage(null, msg);
                setUsername(null);
                setPassword(null);
            } catch (LoginException le) {
                reportUnexpectedLoginError("LoginException", le);
                setUsername(null);
                setPassword(null);
            }
        } else {
            //Utils.showMessage(Utils.MSG_WARN, "Bạn phải thoát khỏi ứng dụng trước khi muốn đăng nhập lại.");
            String loginUrl = "/faces/welcome";
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpServletRequest request =
                (HttpServletRequest)ctx.getExternalContext().getRequest();
            HttpServletResponse response =
                (HttpServletResponse)ctx.getExternalContext().getResponse();
            sendForward(request, response, loginUrl);
        }
        return null;
    }

    private void sendForward(HttpServletRequest request,
                             HttpServletResponse response, String forwardUrl) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        RequestDispatcher dispatcher =
            request.getRequestDispatcher(forwardUrl);
        try {
            dispatcher.forward(request, response);
        } catch (ServletException se) {
            reportUnexpectedLoginError("ServletException", se);
        } catch (IOException ie) {
            reportUnexpectedLoginError("IOException", ie);
        }
        ctx.responseComplete();
    }

    private void reportUnexpectedLoginError(String errType, Exception e) {
        FacesMessage msg =
            new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unexpected error during login",
                             "Unexpected error during login (" + errType +
                             "), please consult logs for detail");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        e.printStackTrace();
    }

    public void setChecklogin(String checklogin) {
        this.checklogin = checklogin;
    }

    public String getChecklogin() {
        SystemSecurity sercu = new SystemSecurity();
        if (sercu.isAuthenticated()) {
          
            FacesContext ctx = FacesContext.getCurrentInstance();
            HttpServletRequest httpRequest = (HttpServletRequest)ctx.getExternalContext().getRequest();
            ExtendedRenderKitService erks =
            Service.getService(ctx.getRenderKit(), ExtendedRenderKitService.class);
            String newPage =httpRequest.getContextPath() + "/faces/welcome";
            String url = "window.open('" + newPage + "','_self');";
            erks.addScript(FacesContext.getCurrentInstance(), url);
        }
        return checklogin;
    }

    public void as(ActionEvent actionEvent) {
        // Add event code here...
    }
}
